app.controller('SalesRouteModalCtrl', function ($scope, $filter, $modalInstance, toaster, param, ajax) {

	$scope.submitting = false;
	$scope.param = param;
	if ($scope.param.data == null) {
		$scope.param.data = {};
	}
	$scope.param.data.sales = { id: 0 };

	$scope.loadTypeList = function () {
		$scope.typeList = [
			{ id: 1, name: "拼车" },
			{ id: 2, name: "包车" },
		];
		//设置默认值
		if ($scope.param.data.type != null) {
			var id = $scope.param.data.type;
			var sel = 0;
			for (var i = 0; i < $scope.typeList.length; i++) {
				sel++;
				if ($scope.typeList[i].id == id) {
					break;
				}
			}
			$scope.typeList.selected = $scope.typeList[sel - 1];
		}
	};
	$scope.loadTypeList();

	//获取线路列表
	$scope.loadRouteList = function () {
		ajax.call(new Req.GET({
			resource: 'route/rt/list'
		})).then(function (result) {
			$scope.routelist = result.result;
			//设置默认值
			if ($scope.param.data.route != null) {
				var id = $scope.param.data.route.id;
				var sel = 0;
				for (var i = 0; i < $scope.routelist.length; i++) {
					sel++;
					if ($scope.routelist[i].id == id) {
						break;
					}
				}
				$scope.routelist.selected = $scope.routelist[sel - 1];
			}
		}, function () { });
	};
	$scope.loadRouteList();

	$scope.serviceList = [];

	$scope.$watch('typeList.selected', function (newVal, oldVal) {
		if (newVal != undefined) {
			var type = newVal.id;
			ajax.call(new Req.GET({
				resource: 'duration/rt/' + type + '/list'
			})).then(function (result) {
				$scope.serviceList = result.result;
			}, function () { });
		}
	});

	$scope.ok = function () {
		if ($scope.myForm.$valid) {
			if ($scope.routelist.selected) {
				$scope.param.data.route = $scope.routelist.selected;
			} else {
				toaster.pop('warning', '提示', '请选择优惠线路!');
				return;
			}
			if ($scope.typeList.selected) {
				$scope.param.data.type = $scope.typeList.selected.id;
			} else {
				toaster.pop('warning', '提示', '请选择类型!');
				return;
			}
			if ($scope.serviceList.selected) {
				$scope.param.data.serviceDuration = $scope.serviceList.selected;
			} else {
				toaster.pop('warning', '提示', '请选择服务时段');
				return;
			}
			$scope.param.data.sales.id = $scope.param.salesId;
			$modalInstance.close($scope.param);
		}
	};

	$scope.cancel = function () {
		$modalInstance.dismiss('cancel');
	};
});



